export default class Http {
    _TAG: any = "Http "
    _versions: string = "v1.0"

    // 单例模式
    private static _instance: Http = null;
    public static getInstance() {
        if (this._instance == null) {
            this._instance = new Http();
        }
        return this._instance;
    }

    // POST请求
    post(url, msgData, callback) {

        const xhr = new XMLHttpRequest();

        // 正式
        // let url = 'https://dev-game.ky311.com/api' + tag;

        // 测试
        // let url = 'https://testgame.ky311.com/api' + tag;

        // 处理数据
        let requestData = '';
        for (let name in msgData) {
            requestData += name + '=' + msgData[name] + '&';
        }

        requestData = requestData == '' ? '' : requestData.substring(0, requestData.length - 1);

        // 设置超时时间1分钟（毫秒）
        xhr.timeout = 60000;

        // 创建一个连接
        xhr.open("POST", url, true);

        // 设置传输头
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        // 发起请求，传输数据
        xhr.send(requestData);

        // 请求超时
        xhr.ontimeout = (err) => {
            if (err) {
                callback({
                    code: 408,
                    msg: '网络异常，请求超时'
                })
            }
        };

        // 请求异常
        xhr.onerror = (err) => {
            if (err) {
                callback({
                    code: 502,
                    msg: '网络异常,找不到服务器'
                })
            }
        };

        // xhr.onload:当xhr.readyState=4时才触发
        // 请求返回
        xhr.onload = function () {
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                let response = xhr.responseText;
                if (response) {
                    let res = JSON.parse(response);
                    // printLog('后端返回的数据', res);
                    if (res.code == 0) {
                        callback({
                            code: 200,
                            msg: res.data
                        });
                    } else {
                        callback({
                            code: 502,
                            msg: res
                        });
                    }
                }
            }
        };
    }
}